package com.freight.auth.service;

import com.freight.auth.form.AppRegisterBody;
import com.freight.common.core.constant.*;
import com.freight.common.core.domain.R;
import com.freight.common.core.exception.ServiceException;
import com.freight.common.core.utils.RsaUtils;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.redis.service.RedisService;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.system.api.RemoteUserService;
import com.freight.system.api.model.LoginUser;
import com.freight.tws.api.RemoteDriverClient;
import com.freight.tws.api.domain.Driver;
import com.freight.tws.api.model.LoginDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * APP登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class AppLoginService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteDriverClient remoteDriverClient;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginDriver login(String phone, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(phone, password))
        {
            throw new ServiceException("用户名/密码必须填写");
        }
        // 利用私钥解密密码
        try {
            password = RsaUtils.decryptByPrivateKey(password);
        } catch (Exception e) {
            throw new ServiceException("密码异常");
        }
        Driver driver = remoteDriverClient.getDriverByPhone(phone);
        if(driver == null) {
            throw new ServiceException("请先注册，再登录");
        }
        if(!SecurityUtils.matchesPassword(password, driver.getPassword())) {
            throw new ServiceException("密码错误");
        }
        if(DictConstants.COMMON_STATE.NO.getKey().equals(driver.getState())) {
            throw new ServiceException("您的账号已被禁用，请联系平台管理员!");
        }

        LoginDriver loginDriver = new LoginDriver();
        loginDriver.setDriverId(String.valueOf(driver.getId()));
        loginDriver.setTelephone(driver.getTelephone());
//            loginDriver.setTenantId(driver.getTenantId());
        loginDriver.setDriver(driver);
        return loginDriver;
    }

    /**
     * 退出
     */
    public void logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            token = token.replace(SecurityConstants.TOKEN_PREFIX, "");
        }
        redisService.deleteObject(CacheConstants.APP_TOKEN_KEY + token);
    }

    /**
     * 注册
     */
    public void register(AppRegisterBody registerBody) {
        if(!StringUtils.isNotBlank(registerBody.getPhone())) {
            throw new ServiceException("手机号不能为空");
        }
        //判断验证码是否正确
        String verifyCode = redisService.getCacheObject(SmsConstants.CACHE_SMS_VERFY_CODE + registerBody.getPhone());
        if(verifyCode == null) {
            throw new ServiceException("验证码已过期");
        }
        if(!verifyCode.equals(registerBody.getCode())) {
            throw new ServiceException("验证码输入错误");
        }

        // 查询手机号是否注册为了货源方
        R<LoginUser> userInfo = remoteUserService.getUserInfo(registerBody.getPhone(), SecurityConstants.INNER);
        if (R.FAIL != userInfo.getCode()) {
            throw new ServiceException("手机号已注册为货源方, 无法注册");
        }

        Driver exsit = remoteDriverClient.getDriverByPhone(registerBody.getPhone());
        if(exsit != null) {
            throw new ServiceException("手机号已注册");
        }
        Driver driver = new Driver();
        driver.setTelephone(registerBody.getPhone());
        driver.setDriverName(registerBody.getPhone());
        if(StringUtils.isNotBlank(registerBody.getPassword())) {
            driver.setPassword(registerBody.getPassword());
        }

        boolean result = remoteDriverClient.regist(driver);
        if(!result) {
            throw new ServiceException("注册失败");
        }
    }

}
